package de.hwrberlin.remo.algorithm.backwardchaining;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.ui.dialogs.ListSelectionDialog;

import de.hwrberlin.remo.algorithm.AlgorithmInitializer;
import de.hwrberlin.remo.algorithm.InferenzAlgorithm;
import de.hwrberlin.remo.model.KnowledgeBase;
import de.hwrberlin.remo.model.Rule;

/**
 * This class initializes the backward chaining algorithm.
 * 
 * 
 * @author Mario Sänger (IT 09)
 * @version 1.0
 *
 */
public class BackwardChainingInitializer implements AlgorithmInitializer {

	@Override
	public void initializeAlgorithm(InferenzAlgorithm algorithm,
			KnowledgeBase base) {

		List<Rule> selectedGoals = new ArrayList<Rule>();
		
		// Only the backward chaining algorithm can be
		// initialized through this class
		if(algorithm instanceof BackwardChaining) {
			BackwardChaining backchain = (BackwardChaining) algorithm;
			
			List<Rule> input = base.getRules();
			IStructuredContentProvider contentProvider = new ArrayContentProvider();
			
			ListSelectionDialog dialog = new ListSelectionDialog(null, input, contentProvider, labelProvider, "");
			dialog.setTitle("Initialize backward chaining");
			dialog.setMessage("Choose goals you want to verify:");
			dialog.setHelpAvailable(false);
			
			// Show goal selection dialog
			if(dialog.open() == Dialog.OK) {
				
				// Build goal list
				for(Object object : dialog.getResult()) {
					if(object instanceof Rule) {
						selectedGoals.add((Rule) object);
					}
				}
			}
			
			backchain.setGoals(selectedGoals);
		}
	}
	
	private LabelProvider labelProvider = new LabelProvider(){
		@Override
		public String getText(Object element) {
			if(element instanceof Rule) {
				String name = ((Rule)element).getName();
				if(name != null) {
					return name;
				}
			}

			return super.getText(element);
		}
	};
}
